package service

import (
	"gin/common"
	"gin/model"
	"gin/queue"
	"gin/validate"
	"github.com/Gre-Z/common/jtime"
	uuid "github.com/satori/go.uuid"
	teamones_helper "github.com/teamones-open/go-helper"
	"time"
)

func CreateLog(Data validate.AddLog) (resData model.Log, err error) {
	var logModel model.Log
	logModel.Level = Data.Level
	logModel.Operate = Data.Operate
	logModel.Record = Data.Record
	logModel.ModuleCode = Data.ModuleCode
	logModel.LinkId = Data.LinkId
	logModel.CreatedBy = Data.CreatedBy
	logModel.BatchNumber = Data.BatchNumber
	logModel.BelongSystem = Data.BelongSystem

	// 填充UUID
	logModel.Uuid = uuid.NewV4().String()
	logModel.Created = jtime.TstampTime(time.Now().Unix())

	_, err = logModel.Insert()

	resData = logModel

	return
}

func FindLog(Param teamones_helper.SelectQueryParam) (resData model.Log, err error) {
	var logModel model.Log

	resData, err = logModel.Find(Param)

	return
}

func SelectLog(Param teamones_helper.SelectQueryParam) (total int, resData []model.Log, err error) {
	var logModel model.Log

	total, resData, err = logModel.Select(Param)

	return
}

// 记录交易流水
func WriteTransactionRecords(Data validate.AddTransactionRecords) (resData model.TransactionRecords, err error) {
	var transactionRecordsModel model.TransactionRecords

	transactionRecordsModel.Type = Data.Type
	transactionRecordsModel.EntryDirection = Data.EntryDirection
	transactionRecordsModel.LinkId = Data.LinkId
	transactionRecordsModel.BelongSystem = Data.BelongSystem
	transactionRecordsModel.Amount = Data.Amount
	transactionRecordsModel.CreatedBy = Data.CreatedBy

	transactionRecordsModel.Number = common.GenerateNumberString()

	// 填充UUID
	transactionRecordsModel.Uuid = uuid.NewV4().String()
	transactionRecordsModel.Created = jtime.TstampTime(time.Now().Unix())

	_, err = transactionRecordsModel.Insert()

	resData = transactionRecordsModel

	return
}

// 记录monolog日志
func WriteMonologRecords(Data validate.AddMonolog) (resData model.Monolog, err error) {
	var monologModel model.Monolog

	monologModel.Level = Data.Level
	monologModel.RequestParam = Data.RequestParam
	monologModel.Route = Data.Route
	monologModel.Record = Data.Record
	monologModel.BelongSystem = Data.BelongSystem

	// 填充UUID
	monologModel.Created = jtime.TstampTime(time.Now().Unix())

	_, err = monologModel.Insert()

	resData = monologModel

	return
}

// SelectMonoLog  系统错误日志查询
func SelectMonoLog(Param teamones_helper.SelectQueryParam) (total int, resData []model.Monolog, err error) {
	var monoLogModel model.Monolog

	total, resData, err = monoLogModel.Select(Param)

	return
}

// WriteRequestRecords 记录monolog日志
func WriteRequestRecords(Data []validate.RequestLog) (err error) {
	err = queue.SendSaveLogToQueue(Data)
	return err
}
